package com.foreknow.util;

import com.foreknow.bean.Person;

import java.sql.*;
import java.util.ArrayList;
import java.util.List;

/**
 * JDBC
 */
public class DBUtil {
    public static void main(String[] args)  {

        try {
            //1.加载驱动程序
            Class.forName("oracle.jdbc.driver.OracleDriver");
            //2.获取连接
            Connection conn =  DriverManager.getConnection("jdbc:oracle:thin:@localhost:1521:orcl","scott","tiger");
            //3.获取到statement对象用于执行增删改查
            //            Statement stmt = conn.createStatement();
            //使用预处理
            PreparedStatement pstmt = conn.prepareStatement("select * from person where name=? and pass=?");
            //将？替换具体的值
            pstmt.setString(1,"tom");
            pstmt.setString(2,"123456");
            //4.将查询到的结果保存到结果集中
            ResultSet rs = pstmt.executeQuery();
            List<Person> list = new ArrayList<>();
            while (rs.next()){
                int id = rs.getInt("ID");
                String name = rs.getString("NAME");
                //创建一个对象
                Person person = new Person();
                person.setId(id);
                person.setName(name);
                //将对象保存到List集合中
                list.add(person);
            }
            for (Person person:list) {
                System.out.println(person.getId()+"----"+person.getName());
            }
            //5.释放资源
            rs.close();
            pstmt.close();
            conn.close();
        } catch (ClassNotFoundException e) {
            e.printStackTrace();
        } catch (SQLException e) {
            e.printStackTrace();
        }
    }
}
